package com.shxy.cloudclassroom.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shxy.cloudclassroom.entity.pojo.*;
import com.shxy.cloudclassroom.mapper.AssignmentMapper;
import com.shxy.cloudclassroom.service.*;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.shxy.cloudclassroom.utils.SystemConstant.LOGIN_USER;

@Service
public class AssignmentServiceImpl extends ServiceImpl<AssignmentMapper, Assignment> implements AssignmentService {
    
    @Resource
    private AssignmentSubmissionService assignmentSubmissionService;
    
    @Resource
    private OssService ossService;
    
    @Resource
    private MajorService majorService;
    
    @Resource
    private UserService userService;

    @Override
    // 获取作业列表
    public List<Assignment> getAssignmentList(Page<Assignment> assignmentPage, LambdaQueryWrapper<Assignment> wrapper) {
        return this.list(assignmentPage, wrapper);
    }

    @Override
    // 发布作业
    public Map<String, Object> publishAssignment(Assignment assignment, MultipartFile file, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            //校验用户是否过期
            User user = (User) session.getAttribute(LOGIN_USER);
            if (user == null) {
                result.put("success", false);
                result.put("redirect", "redirect:/login");
                return result;
            }
            if (file == null) {
                result.put("success", false);
                result.put("redirect", "assignment/publish");
                return result;
            }
            String fileUrl = ossService.uploadAvatar(file);
            assignment.setFileUrl(fileUrl);
            assignment.setStatus(1);
            assignment.setUpdatedTime(LocalDateTime.now());
            assignment.setUploaderId(user.getId());
            assignment.setCreatedTime(LocalDateTime.now());
            int compareResult = LocalDateTime.now().compareTo(assignment.getDeadline());
            //截至时间是否符合规则
            if (compareResult > 0) {
                result.put("success", false);
                result.put("redirect", "assignment/publish");
                return result;
            }
            boolean flag = this.save(assignment);
            result.put("success", true);
            result.put("redirect", "redirect:/assignment/list");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "发布作业失败: " + e.getMessage());
        }
        return result;
    }

    @Override
    // 提交作业
    public Map<String, Object> submitAssignment(AssignmentSubmission submission, MultipartFile file, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            //校验用户是否过期
            User user = (User) session.getAttribute(LOGIN_USER);
            if (user == null) {
                result.put("success", false);
                result.put("redirect", "redirect:/login");
                return result;
            }

            // 检查文件是否为空
            if (file.isEmpty()) {
                result.put("success", false);
                result.put("message", "文件为空!");
                return result;
            }
            // 检查是否已经提交过
            AssignmentSubmission existingSubmission = assignmentSubmissionService.query()
                    .eq("assignment_id", submission.getAssignmentId())
                    .eq("user_id", user.getId())
                    .one();

            if (existingSubmission != null && existingSubmission.getStatus() == 1) {
                result.put("success", false);
                result.put("message", "重复提交!");
                return result;
            }
            // 上传文件到OSS
            String fileUrl = ossService.uploadAvatar(file);
            // 设置提交记录属性
            submission.setFileUrl(fileUrl);
            submission.setUserId(user.getId());
            submission.setStatus(1); // 1表示已提交
            submission.setSubmittedTime(LocalDateTime.now());
            // 保存提交记录
            boolean saved = assignmentSubmissionService.save(submission);
            result.put("success", saved);
            if (saved) {
                result.put("message", "作业提交成功");
            } else {
                result.put("message", "作业提交失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "提交过程中发生错误: " + e.getMessage());
        }
        return result;
    }

    @Override
    // 获取作业详情
    public com.shxy.cloudclassroom.entity.vo.AssignmentDetailVO getAssignmentDetail(Integer id, HttpSession session) {
        try {
            //校验用户是否过期
            User user = (User) session.getAttribute(LOGIN_USER);
            if (user == null) {
                return null;
            }
            // 查询作业详情
            Assignment assignment = this.query().eq("id", id).one();
            if (assignment == null) {
                return null;
            }
            // 查询关联的专业
            Integer majorId = assignment.getMajorId();
            Major major = majorService.getById(majorId);

            // 查询用户的作业提交记录
            AssignmentSubmission assignmentSubmission = assignmentSubmissionService.query()
                    .eq("assignment_id", assignment.getId())
                    .eq("user_id", user.getId()) // 关联提交id
                    .one();

            // 如果没有提交记录，创建一个新的空记录
            if (assignmentSubmission == null) {
                assignmentSubmission = new AssignmentSubmission();
                assignmentSubmission.setAssignmentId(assignment.getId());
                assignmentSubmission.setUserId(user.getId());
                assignmentSubmission.setComment("");
                assignmentSubmission.setStatus(0); // 0表示未提交
            }

            // 封装到VO对象
            com.shxy.cloudclassroom.entity.vo.AssignmentDetailVO assignmentDetailVO = new com.shxy.cloudclassroom.entity.vo.AssignmentDetailVO();
            assignmentDetailVO.setId(assignment.getId());
            assignmentDetailVO.setTitle(assignment.getTitle());
            assignmentDetailVO.setDescription(assignment.getDescription());
            assignmentDetailVO.setMajorName(major.getName());
            assignmentDetailVO.setMajorId(major.getId());
            assignmentDetailVO.setDeadline(assignment.getDeadline());
            assignmentDetailVO.setFileUrl(assignment.getFileUrl());
            assignmentDetailVO.setStatus(assignment.getStatus());
            assignmentDetailVO.setCreatedTime(assignment.getCreatedTime());
            assignmentDetailVO.setUpdatedTime(assignment.getUpdatedTime());
            assignmentDetailVO.setAssignmentSubmission(assignmentSubmission);
            
            // 如果是管理员，获取所有提交记录
            if ("ordinaryAdmin".equals(user.getRole()) || "superAdmin".equals(user.getRole())) {
                List<AssignmentSubmission> submissions = assignmentSubmissionService.list(
                        new LambdaQueryWrapper<AssignmentSubmission>()
                                .eq(AssignmentSubmission::getAssignmentId, assignment.getId())
                );

                // 获取所有提交作业的用户信息
                List<Long> userIds = submissions.stream()
                        .map(AssignmentSubmission::getUserId)
                        .distinct()
                        .toList();

                List<User> users = userService.listByIds(userIds);
                Map<Long, String> userMap = users.stream()
                        .collect(Collectors.toMap(User::getId, User::getUsername));

                assignmentDetailVO.setSubmissions(submissions);
                assignmentDetailVO.setUserMap(userMap);
            }

            return assignmentDetailVO;
        } catch (Exception e) {
            return null;
        }
    }
}